<?php 
namespace common\service;
use common\model\sell66\UserOrder;
use common\model\sell66\UserOrderDetail;
use think\Cache;
use common\libs\Curl;
use common\libs\StringHelper;
/**
 * 获取用户库存
 */
class InvService{

	public static $instance = null;
	const USER_STEAM_INVENTORY_KEY = 'user_steam_inventory_key_';
	const USER_STEAM_INVENTORY_STATUS = 'user_steam_inventory_key_STATUS';
	public  $appIds = array(
 		"730"=>array("app_id"=>730,"name"=>"CS:GO"),
		"570"=>array("app_id"=>570,"name"=>"DOTA2"),
//		"578080"=>array("app_id"=>578080,"name"=>"PUBG")
	);
	
	private function __construct(){
		
	}

	public static function getInstance(){
		if(self::$instance == null){
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	private function checkppId($appId){
		if(!key_exists($appId, $this->appIds)){
			return false;
		}
		return true;
	}
	
	public function getAppIds($appId = 730){
		$result = [];
		foreach ($this->appIds as $id=>$item){
			$result[] = array(
					"appId"=>$id,
					"appName"=>$item['name'],
					"selected"=>($id == $appId)?true:false
			);
		}
		return $result;
	}
	
	private function pageInv($userInventory,$pageNo=1,$pageSize=5,$sort='desc',$keyword='',$order='price'){
		$itemsCount = count($userInventory);
		$offset = ($pageNo - 1) * $pageSize;
		if($itemsCount <= $offset){
			return [
			'totalPage'=>0,
			'currentPage'=>0,
			'list'=>[]
			];
		}

        if($keyword != ''){
            $userInventory = array_filter($userInventory, function($item) use($keyword){
                if(strpos(strtolower($item['market_name']), strtolower($keyword)) !== false) return true;
            });
        }
        $sort = $sort=='desc'? SORT_DESC: SORT_ASC;
        $order = array_column($userInventory, $order);
        array_multisort($order, $sort, $userInventory);
        $itemsCount = count($userInventory);
		$currentInventory = array_slice($userInventory, $offset,$pageSize);
		$totalPage = ceil( $itemsCount / $pageSize );
		$currentPage = $pageNo;
		return [
			'totalPage'=>$totalPage,
			'currentPage'=>$currentPage,
			'list'=>$currentInventory,
		];
	}
	
	public function refreshItem($steamId,$appId = 730){
		$cacheStatusKey = sprintf(INVENTORY_STATUS_STEAMID_APPID,$steamId,$appId);
		$status = Cache::store('redis')->set($cacheStatusKey,0);
		return true;
	}
	public function selectAllItem($steamId,$userId,$status,$appId = 730){
		$cacheKey = sprintf(INVENTORY_KEY_STEAMID_APPID,$steamId,$appId);
		$userInventory = Cache::store('redis')->get($cacheKey);
		if(empty($userInventory)){
			$this->getInv($userId, $steamId, 1, 25);
		}
		$userInventory = Cache::store('redis')->get($cacheKey);
		if($status != 0){//反选
			foreach ($userInventory as &$item){
				$item['selected'] = false;
			}
			
		}else{
			foreach ($userInventory as &$item){
				if($item['recovery']==true){
					$item['selected'] = true;
				}
			}
		}
		Cache::store('redis')->set($cacheKey,$userInventory,600);
		return true;
	}
	public function getInv($userId,$steamId, $page,$limit,$appId=730,$sort='desc',$keyword='',$order='price'){
		if(!$this->checkppId($appId)){
			return -1;
		}
		$cacheKey = sprintf(INVENTORY_KEY_STEAMID_APPID,$steamId,$appId);
		$cacheStatusKey = sprintf(INVENTORY_STATUS_STEAMID_APPID,$steamId,$appId);
		$status = Cache::store('redis')->get($cacheStatusKey);
		$userInventory = Cache::store('redis')->get($cacheKey);
        $inStoreInventory = UserOrderDetail::getInStoreByUserId($userId);
        $ingCount = count($inStoreInventory);

		if($status == 1 && $userInventory){//缓存没有失效
			return $this->pageInv($userInventory,$page,$limit,$sort,$keyword,$order);
		}

        $rsaResponse = Curl::http_get('https://steamcommunity.com/inventory/' . $steamId . '/' . $appId . '/2/?trading=1&count=5000&' . rand(1, 1000), 'zh-cn');
        if ($rsaResponse == 429) {
            $times = 0;
            while ($times < 1) {
                $rsaResponse = Curl::http_get('https://steamcommunity.com/inventory/' . $steamId . '/' . $appId . '/2/?trading=1&count=5000&' . rand(1, 1000), 'zh-cn');
                if ($rsaResponse != 429) {
                    break;
                }
                $times++;
            }
            return -3;
        }
		$rsaResponse = json_decode($rsaResponse, true);

        if ($rsaResponse && $rsaResponse['success'] == false) {
        	return [
				'totalPage'=>0,
				'currentPage'=>0,
				'list'=>[]
			];
        }
        
        if(empty($rsaResponse['assets'])){
        	return [
				'totalPage'=>0,
				'currentPage'=>0,
				'list'=>[]
			];
        }
      
       	$RespInventory['rgInventory'] = $rsaResponse['assets'];
       	$RespInventory['rgDescriptions'] = $rsaResponse['descriptions'];

        foreach ($RespInventory['rgInventory']  as $key => &$value) {
			foreach ($RespInventory['rgDescriptions'] as $row => $desc) {
				if ($value['classid'] == $desc['classid'] && $value['instanceid'] == $desc['instanceid']) {
				    if(!$desc['tradable']) {
                        unset($RespInventory['rgInventory'][$key]);
                    }else{
                        $value['market_hash_name'] = $desc['market_hash_name'];
                        $value['tradable'] = $desc['tradable'];
                    }
				}
			}
        }

        $ratio = UserService::getInstance()->plusRatio($userId,$appId);
        $TempInventory = ItemPriceService::getInstance()->calculatePrice($RespInventory,$appId);
        $rgInventory = [];
       
        foreach ($TempInventory as $key=>$item){
        	$item['appId'] = $appId;
        	$rgInventory[$key+1] = $item;
        }
        $userInventory = array();
       
        foreach ($rgInventory as $index=>$item){
        	$tempItem['positionId'] = $index;
        	$tempItem['appId'] = $item['appId'];
        	$tempItem['id'] = $item['assetid'];
        	$tempItem['classid'] = $item['classid'];
        	$tempItem['instanceid'] = $item['instanceid'];
        	$tempItem['amount'] = $item['amount'];
        	$tempItem['price'] = $item['price'];
        	$tempItem['selected'] = false;
        	$tempItem['originPrice'] = $item['originPrice'];
        	$tempItem['recovery'] = true;
        	$tempItem['market_hash_name'] = $item['market_hash_name'];
        	$tempItem['market_name'] = $item['desc']['market_name'];
        	$tempItem['exterior'] = $item['exterior'];
        	$tempItem['rarity'] = $item['rarity'];
        	$tempItem['item_second'] = $item['item_second'];
        	$tempItem['plus_price'] = $item['price'];
        	$tempItem['desc'] =$item['desc'];
        	$tempItem['image'] =StringHelper::getSteamImageUrl($item['appId'], $item['market_hash_name']);
        	$userInventory[] = $tempItem;
        }
        Cache::store('redis')->set($cacheKey,$userInventory,600);
        Cache::store('redis')->set($cacheStatusKey, 1,600);

        $returnInv = [];
        foreach ($userInventory as $item){
            if(empty($item['recovery'])){
                continue;
            }
            $key = $item['id'];
            if(array_key_exists($key, $inStoreInventory)){
                continue;
            }
            $returnInv[] = $item;
        }
        return $this->pageInv($returnInv,$page,$limit,$sort,$keyword,$order);
	}
	
	public function getSelectedItemPrice($steamId,$userId,$appId=730){
		$totalPrice = 0;
		$totalOriginPrice = 0;
		$number = 0;
		$cacheKey = sprintf(INVENTORY_KEY_STEAMID_APPID,$steamId,$appId);
		$userInventory = Cache::store('redis')->get($cacheKey);
		$ratio = UserService::getInstance()->plusRatio($userId,$appId);
		$balance = WalletService::getInstance()->info($userId);
		$result['ratio'] = $ratio;
		
		if(empty($userInventory)){
			return [
			'totalPrice' => $totalPrice,
			'originPrice' => $totalOriginPrice,
			'withdrawPrice' =>number_format($totalPrice + $balance['balance'], 2, '.', ''),
			'number'=> 0,
			'ratio' => $ratio,
			'balance' => $balance
			];
		}
		foreach($userInventory as $item){
			if($item['selected'] == true && $item['recovery']==true){
				$number += 1;
				$totalPrice += $item['plus_price'];
				$totalOriginPrice += $item['price'];
			}
		}
		
		return [
			'totalPrice'=> sprintf('%.2f',number_format($totalPrice,2, '.', '')),
			'originPrice'=>sprintf('%.2f', $totalOriginPrice),
			'withdrawPrice' => sprintf('%.2f', $totalPrice+number_format($balance['balance'], 2, '.', '')),
			'number'=>$number,
			'ratio' => $ratio,
			'balance' => $balance
			];
	}
	public function getUserSelectItem($steamId,$appIds = array(730)){
		$res = [];
		$result = [];
		foreach ($appIds as $appId){
			$cacheKey = sprintf(INVENTORY_KEY_STEAMID_APPID,$steamId,$appId);
			$userInventory = Cache::store('redis')->get($cacheKey);
			if(empty($userInventory)){
				$this->resetUserInventoryStatus($steamId, $appId);
				continue;
			}
			foreach ($userInventory as $seleteItem){
				if($seleteItem['selected'] == true){
					$result[$seleteItem['appId']][] = $seleteItem;
				}
			}
		}
		if(empty($result)){
			return [];
		}
		foreach ($result as $appId=>$items){
			$res[] = array("appId"=>$appId,'items'=>$items);
		}
		return $res;
	}
	
	/**
	 * 标记 user库存是否更新 
	 * @param unknown $steamId
	 * @param unknown $appId
	 * @param unknown $status
	 */
	public function resetUserInventoryStatus($steamId,$appId,$status = 0){
		$statusKey = sprintf(INVENTORY_STATUS_STEAMID_APPID,$steamId,$appId);
		$Key = sprintf(INVENTORY_KEY_STEAMID_APPID,$steamId,$appId);
		$a = Cache::store('redis')->set($Key,$status);
		$b = Cache::store('redis')->set($statusKey,$status);
	}
	

	public function selectItem($userId,$positionId,$steamId,$appId = 730){
		$cacheKey = sprintf(INVENTORY_KEY_STEAMID_APPID,$steamId,$appId);
		$userInventory = Cache::store('redis')->get($cacheKey);
		if(empty($userInventory)){
			return -1;//请重新刷新缓存
		}

		$seletedItem = [];
		
		foreach ($userInventory as $key=>$item){
			if($item['positionId'] == $positionId){
				$seletedItem = $item;
				$positionKey  = $key;
				break;
			}
		}
		if(empty($seletedItem)){
			return -1;//请重新刷新缓存
		}
		
		$seletedItem = ItemPriceService::getInstance()->calculateItemPrice($seletedItem,$appId);
		if($seletedItem['recovery'] !== true){
			//return -2;//当前物品不收 请重新刷新
		}
		
		$seletedItem['selected'] = $seletedItem['selected'] == false ? true : false;
		$userInventory[$positionKey] = $seletedItem;
		$a = Cache::store('redis')->set($cacheKey,$userInventory,600);
		return [
			 'selected'=>$seletedItem['selected'],
			 'originPrice'  =>$seletedItem['originPrice'],
			 'price'  =>$seletedItem['price'],
			 'plus_price'  =>$seletedItem['plus_price'],
			 'recovery'  =>$seletedItem['recovery'],
			 'positionId'  =>$seletedItem['positionId']
			];
	}
	
}